package com.heisen.file.domin;

import com.heisen.base.exception.RRException;
import com.heisen.file.dto.FileDto;
import com.heisen.file.entity.OpFile;
import com.heisen.file.enums.FileStatusEnum;
import com.heisen.file.service.IOpFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author sen
 * @description
 * @date 2024/2/27 16:04
 */
@Slf4j
@Component
public class FileStorageManager {



    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IOpFileService opFileService;


//    @Override
//    public void afterPropertiesSet() throws Exception {
//        log.info("当前文件存储使用："+this.fileServiceName);
//        this.fileStorageService = this.fileStorageServiceMap.get(this.fileServiceName);
//        Objects.requireNonNull(this.fileStorageService, "没有找到文件存储后端服务：" + this.fileServiceName);
//    }


    public List<Serializable> upload(MultipartFile[] files , FileDto fileDto) {
        List<OpFile> upload = fileStorageService.upload(files, fileDto);
        boolean b = opFileService.saveBatch(upload);
        if(!b) throw new RRException("文件保存失败");
        return  upload.stream().map(file -> file.getId()).collect(Collectors.toList());
    }


    public String fileUrl(String fileId) {
        OpFile byId = opFileService.getFileByFileId(fileId);
        return  fileStorageService.fileUrl(byId.getStoreService(),byId.getStorePath());
    }


    public Boolean delete(String fileId) {
        OpFile byId = opFileService.getFileByFileId(fileId);
        byId.setStatus(FileStatusEnum.DELETE.getStatus());
        return  opFileService.updateById(byId);
    }


    public void download(@RequestParam(value = "fileId")String fileId, HttpServletResponse response) {
        OpFile byId = opFileService.getFileByFileId(fileId);
        fileStorageService.download(byId.getStoreService(),byId.getStorePath(),response);
    }
}
